package com.ahstu.learning.player;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.ahstu.learning.R;
import com.ahstu.learning.bean.CourseMessage;
import com.ahstu.learning.SubjectActivity.Subject;
import com.ahstu.learning.bean.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
public class CommentFragment extends Fragment {

	protected static final int SUCCESS_GET_DATA = 0;
	//private ArrayAdapter<String> adapter;
	String objectid;
	private ListView listview;
	private DataService service;
	private ArrayList<Map<String, String>> data;// 加载的总数据
	private boolean finish = true;// 是否加载完成
	private SimpleAdapter simpleAdapter;
	private View footer;
	private ImageView send_message;
	private ArrayList<Map<String, String>> comment_list = new ArrayList<Map<String, String>>();
	private Map<String, String> comment_map;
	private int comment_count = 0;
	private String course_type;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case SUCCESS_GET_DATA:
					ArrayList<Map<String, String>> result = ((ArrayList<Map<String, String>>) msg.obj);
					data.addAll(result);
					// 让listview自动刷新
					simpleAdapter.notifyDataSetChanged();
					finish = true;
					// 将页脚删除掉
					if (listview.getFooterViewsCount() > 0) {
						listview.removeFooterView(footer);
					}
					break;
				default:
					break;
			}
		};
	};
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.commentfragment, null);
		listview = (ListView) view.findViewById(R.id.pinglunlistview);
		send_message= (ImageView) view.findViewById(R.id.send_message);
		service = new DataService();
		data = new ArrayList<Map<String, String>>();
		ArrayList<Map<String, String>> result = service.getData(0, 10);
		data.addAll(result);

		footer = View.inflate(getActivity(), R.layout.footer, null);

		// 在增加listview的页脚之前，需要提前设置一次
		listview.addFooterView(footer);
		// 然后再次将页脚删除掉
		listview.removeFooterView(footer);
		// 滚动监听事件
		listview.setOnScrollListener(new MyOnScrollListener());
		objectid = getActivity().getIntent().getStringExtra("objectid");
		Subject subject = new Subject();
		comment_list = subject.getCourse_commemt_list();
		course_type = subject.getCourseType();
		simpleAdapter = new SimpleAdapter(getActivity(), data, R.layout.comment_item, new String[]{"username", "comment"}, new int[]{R.id.username, R.id.tv_info});
		listview.setAdapter(simpleAdapter);

		init();
		return view;
	}


	private void init() {

		send_message.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivityForResult(new Intent(getActivity(), CommentActivity.class), 1);
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		//super.onActivityResult(requestCode, resultCode, data);
//        String commment_str=data.getStringExtra("comment");
//        Toast.makeText(getActivity(),commment_str,Toast.LENGTH_LONG).show();
		if (resultCode == 0 && requestCode == 1) {
			if (data.getExtras().getString("comment").toString().equals("")) {
			} else {
				String comment = data.getExtras().getString("comment").toString();
				User user = BmobUser.getCurrentUser(getActivity(), User.class);
				String usename = user.getUsername();
				Map<String, String> course_map = new HashMap<String, String>();
				course_map.put("username", usename);
				course_map.put("comment", comment);
				comment_list.add(course_map);
				final BmobObject course_message = new CourseMessage();

				BmobQuery<CourseMessage> query=new BmobQuery<>();
                query.addWhereEqualTo("CourseType",course_type);
				query.addWhereEqualTo("objectid",objectid);
				query.findObjects(getActivity(), new FindListener<CourseMessage>(){
					@Override
					public void onSuccess(List<CourseMessage> list) {
						course_message.setValue("comment", comment_list);
					}

					@Override
					public void onError(int i, String s) {
						Toast.makeText(getActivity(),"error",Toast.LENGTH_SHORT).show();
					}
				});

				course_message.update(getActivity(), objectid, new UpdateListener() {
					@Override
					public void onSuccess() {
						/**
                         * 同步评论数据存在问题
						 */
						Toast.makeText(getActivity(), "提交成功", Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onFailure(int i, String s) {
						Toast.makeText(getActivity(), "提交失败" + s, Toast.LENGTH_LONG).show();
					}
				});
			}
		}
	}

	//加载的数据类
	public class DataService {

		//加载数据
		public ArrayList<Map<String, String>> getData(int startPosition, int offset) {
			ArrayList<Map<String, String>> data = new ArrayList<Map<String, String>>();
			int i = 0;
			for (; comment_count < comment_list.size(); comment_count++) {
				if (i == 10)
					return data;
				comment_map = comment_list.get(comment_count);
				data.add(comment_map);

				i++;
			}
			return data;
		}
	}

	private final class MyOnScrollListener implements OnScrollListener {
		// 加载的总页数
		private int countPage = comment_list.size() / 10;

		// 每页加载10条数据
		private int pageSize = 10;

		// 滚动状态发生改变时
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			Log.i("i", " scrollState " + scrollState);
		}

		// 当list开始滚动时
		public void onScroll(AbsListView view, int firstVisibleItem,
							 int visibleItemCount, int totalItemCount) {
			// 最下面的条目数
			final int totalCount = firstVisibleItem + visibleItemCount;
			int currentPage = totalCount / pageSize;// 当前页
			int nextPage = currentPage + 1;// 下一页
			if (comment_list.size() % 10 > 0)
				countPage++;
				
			// 当翻到最后一条数据时
			if (totalCount == totalItemCount && nextPage <= countPage && finish) {
				// 已经移动到了listview的最后
				finish = false;
				// 添加页脚
				listview.addFooterView(footer);
				new Thread() {
					public void run() {
						SystemClock.sleep(1000);
						ArrayList<Map<String, String>> result = service.getData(totalCount + 1,
								pageSize);
						Message msg = new Message();
						msg.what = SUCCESS_GET_DATA;
						msg.obj = result;
						mHandler.sendMessage(msg);
					};
				}.start();
			}
		}
	}
}
